<template>
  <div
    id="SelfAdaption"
    :style="{
      ...styles,
    }"
  >
    <slot>SelfAdaption</slot>
  </div>
</template>

<script>
  import { onMounted, onUnmounted, ref } from 'vue';
  import { throttle } from 'lodash';

  export default {
    /**
     * @description 自适应分辨率
     */
    props: {
      /**
       * @props
       * @property {Array<number>} resolution 分辨率
       * @property {Function} resizeCallback 重置分辨率包装函数
       * @property {Function} resizeCbDestroyed 销毁包装函数
       */
      resolution: {
        type: Array,
        default: () => [
          document.documentElement.clientWidth,
          document.documentElement.clientHeight,
        ],
        validator(val) {
          return val.every(item => item > 0);
        },
      },
      resizeCallback: {
        type: Function,
        default: () => {},
      },
      resizeCbDestroyed: {
        type: Function,
        default: () => {},
      },
    },
    setup(props) {
      const styles = ref({});
      const resize = throttle(() => {
        const { width, height } = document.getElementsByTagName('body')[0].getBoundingClientRect();
        const scaleX = Number(width / props.resolution[0]).toFixed(6);
        const scaleY = Number(height / props.resolution[1]).toFixed(6);
        styles.value = {
          width: `${document.documentElement.clientWidth}px`,
          height: `${document.documentElement.clientHeight}px`,
          transform: `scaleX(${scaleX}) scaleY(${scaleY})`,
          transformOrigin: 'left top',
        };
        props.resizeCallback();
        if (scaleX < 0.9 || scaleX > 1.1 || scaleY < 0.9 || scaleY > 1.1) {
          window.location.reload();
        }
      }, 300);
      onMounted(() => {
        resize();
        window.addEventListener('resize', resize);
      });
      onUnmounted(() => {
        window.removeEventListener('resize', resize, true);
        props.resizeCbDestroyed();
      });
      return {
        resize,
        styles,
      };
    },
  };
</script>

<style lang="scss" scoped>
  #SelfAdaption {
    height: 100%;
    position: relative;
    overflow: hidden;
  }
</style>
